#include "containerPrototype.hpp"
#include "MiscUtils/TdrMisc/SEngine.h"

using namespace std;

int ContainerHolderSlave::SampleContainer::SampleSlot::toStr(int indent) {
	string line;
	TFormater::indent(indent, line);
	line += "S" + TFormater::int2str(virtualIdx);
	line += ", Rw=" + TFormater::int2str(rawReading);
	line += ", Trsh=" + TFormater::int2str(threshold);
	line += ", Ocu=" + TFormater::int2str(isOccupied);

	TLogger::writeLine(line);
	return 1;
}

void ContainerHolderSlave::SampleContainer::resize(int size) {

}

int ContainerHolderSlave::SampleContainer::size() {
	return slots.size();
}


void ContainerHolderSlave::ContainerStatuses::resize(int layerNum, int slidePerLayer) {
	containers.resize(layerNum);
	for (int idx = 0; idx < layerNum; idx++) {
		containers[idx].containerIdx = idx;
		containers[idx].resize(slidePerLayer);
	}
}

void ContainerHolderSlave::ContainerStatuses::forceUpdateAll() {
	for (auto& ctn : containers) {
		for (auto& slot : ctn.slots) {
			slot.isOccupied = -1;
		}
	}
}

void ContainerHolderSlave::ContainerStatuses::restartReadout() {
	readOutLayerIdx = 0;
	readOutPosIdx = 0;
}

int ContainerHolderSlave::ContainerStatuses::readOut(int* layerIdx, int* posIdx, int* rawReading, int* threshold, int* isOccupied) {
	while (readOutLayerIdx < containers.size()) {
		auto& container = containers[readOutLayerIdx];
		if (readOutPosIdx > container.size()) {
			//TLogger::writeLine("1 ");
			readOutLayerIdx++;
			readOutPosIdx = 0;
			continue;
		}
		auto& pData = container.slots[readOutPosIdx++];
		if (readOutVerboseLv == 0) {
			if (pData.isOccupiedDifferent == 0) {
				return 0;
			}
		}
		ProcS::setIfNotNullPtr(container.containerIdx, layerIdx);
		ProcS::setIfNotNullPtr(pData.virtualIdx, posIdx);
		ProcS::setIfNotNullPtr(pData.rawReading, rawReading);
		ProcS::setIfNotNullPtr(pData.threshold, threshold);
		ProcS::setIfNotNullPtr(pData.isOccupied, isOccupied);
		return 1;
	}
	//TLogger::writeLine("Cannot readout " + TFormater::int2str(readOutLayerIdx) + " / " + TFormater::int2str(_layers.size()));
	return 0;
}

void ContainerHolderSlave::ContainerStatuses::print() {

}

void ContainerHolderSlave::ContainerStatuses::clear() {
	containers.resize(0);
	containers.shrink_to_fit();
}

int ContainerHolderSlave::forceUpdateAll() {
	_status.forceUpdateAll();
	return 1;
}

// mode==0: all, mode==1: only changed
int ContainerHolderSlave::startReadOut(int mode) {
	_status.readOutVerboseLv = mode;
	_status.restartReadout();
	return 1;
}
int ContainerHolderSlave::readOut(int* layerIdx, int* posIdx, int* rawReading, int* threshold, int* isOccupied) {
	return _status.readOut(layerIdx, posIdx, rawReading, threshold, isOccupied);
}